import React from 'react'
import { Button, Divider, Icon, Input, Table, Tag } from 'antd'
import Highlighter from 'react-highlight-words'
import { FormattedMessage } from 'react-intl'
import _ from 'lodash'

export default class TaskStatusBox extends React.Component {
  state = {
    searchText: ''
  }

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({setSelectedKeys, selectedKeys, confirm, clearFilters}) => (
      <div style={{padding: 8}}>
        <Input
          ref={node => {
            this.searchInput = node
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{width: 188, marginBottom: 8, display: 'block'}}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{width: 90, marginRight: 8}}
        >
          Search
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{width: 90}}>
          Reset
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{color: '#1890ff'}}/>
    ),
    onFilter: (value, record) => (record[dataIndex] || '')
      .toString()
      .toLowerCase()
      .includes(value.toLowerCase())
    ,
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select())
      }
    }
    ,
    render: text => (
      <Highlighter
        highlightStyle={{backgroundColor: '#ffc069', padding: 0}}
        searchWords={[this.state.searchText]}
        autoEscape
        textToHighlight={text.toString()}
      />
    ),
  })

  handleSearch = (selectedKeys, confirm) => {
    confirm()
    this.setState({searchText: selectedKeys[0]})
  }

  handleReset = clearFilters => {
    clearFilters()
    this.setState({searchText: ''})
  }

  formatTags = (item) => {
    if (!item) return ''

    const tagColors = item.split(',')
    return tagColors.map((item) => {
      const tagColor = item.split('|')
      return <Tag color={tagColor[1]}>{tagColor[0]}</Tag>
    })
  }
  getColumns = assignmentsFinishSpeedOverview => {
    let columns = [{
      title: <FormattedMessage id='姓名'/>,
      dataIndex: 'name',
      width: 100,
      fixed: 'left'
    }, {
      title: <FormattedMessage id='tags'/>,
      fixed: 'left',
      width: 50,
      dataIndex: 'tag',
      ...this.getColumnSearchProps('tag'),
      render: (item) => {
        return <span>{this.formatTags(item)}</span>
      }
    }]
    _.unionBy(assignmentsFinishSpeedOverview, 'assignmentId')
      .sort((a, b) => a.assignmentId - b.assignmentId)
      .forEach(item => {
        columns.push({
          title: <span>{item['任务卡']}<Divider type='vertical'/>{item['作业']}</span>,
          width: 200,
          dataIndex: item.assignmentId,
          render: (text, record) => {
            const format = time => time ? time.replace('T', ' ') : '?'

            return <span>{
              this.props.model
                ? text
                : <span> {format(record.startTime)} - <br/>
                  {format(record.endTime)}</span>
            }
                </span>
          }
        })
      })
    columns.push({
      title: '总时间',
      dataIndex: 'total',
      width: 200,
      defaultSortOrder: 'descend',
      sorter: (a, b) => {
        const aFinishCount = a.assignments.filter(item => !!item.startTimestamp && !!item.endTimestamp).length
        const bFinishCount = b.assignments.filter(item => !!item.startTimestamp && !!item.endTimestamp).length
        if (aFinishCount === bFinishCount) {
          return this.statisticTotalTime(b.assignments) - this.statisticTotalTime(a.assignments)
        }
        return aFinishCount - bFinishCount
      },
      render: (text, record) => {
        return this.formatDurationTime(record.assignments)
      }
    })
    return columns
  }

  formatDurationTime = assignmentsDuration => {
    const finishCount = assignmentsDuration.filter(item => !!item.startTimestamp && !!item.endTimestamp).length
    return <span>{finishCount}/{assignmentsDuration.length} | {this.formatTime(this.statisticTotalTime(assignmentsDuration))}</span>
  }

  statisticTotalTime = assignments => {
    return assignments.reduce((value, current) => {
      const {startTimestamp, endTimestamp} = current
      if (!startTimestamp || !endTimestamp) {
        return value
      }
      value += endTimestamp - startTimestamp
      return value
    }, 0)
  }
  formatTime = timestamp => {
    const hours = parseInt(timestamp / 60 / 60)
    const minutes = parseInt(timestamp / 60) - hours * 60

    return `${hours} H ${minutes} min`
  }
  getData = assignmentsQuizzesStatus => {
    const groupByNameAssignments = _.groupBy(assignmentsQuizzesStatus, 'name')
    return Object.keys(groupByNameAssignments).map(name => {
      const studentAssignments = groupByNameAssignments[name]
      let column = {name, tag: studentAssignments[0].tag, assignments: []}
      const groupByTaskAssignments = _.groupBy(studentAssignments, 'taskId')
      Object.keys(groupByTaskAssignments).forEach(taskId => {
        const taskAssignments = groupByTaskAssignments[taskId]
        taskAssignments.forEach(item => {
          column.startTime = item.startTime
          column.endTime = item.endTime
          column[item.assignmentId] = this.formatDurationTime([item])
          column.assignments.push(item)
        })
      })
      return column
    })
  }

  render () {
    const {assignmentsFinishSpeedOverview} = this.props
    const columns = this.getColumns(assignmentsFinishSpeedOverview)
    const data = this.getData(assignmentsFinishSpeedOverview)

    return <Table columns={columns}
                  dataSource={data}
                  pagination={false}
                  bordered
                  size='small'
                  scroll={{x: 'max-content'}}
    />
  }
}
